using Services;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DialogUI_TaChiE : MonoBehaviour
{
    private DialogSystem dialogSystem;
    private EventSystem eventSystem;

    public ETaChiEPosition postion;
    [SerializeField]
    private Color dullColor;
    private Image image;
    private ColorChange colorChange;

    private void Awake()
    {
        eventSystem = ServiceLocator.Get<EventSystem>();
        image = GetComponent<Image>();
        colorChange = new ColorChange();
        colorChange.Tick += SetColor;
        dialogSystem = GetComponentInParent<DialogSystem>();
        eventSystem.AddListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
    }

    private void Start()
    {
        dialogSystem.ShowSingleDialog += ShowTaChiE;
        dialogSystem.ShowSelection += OnShowSelection;
    }

    private void ShowTaChiE(SingleDialog dialog)
    {
        if (dialog.TachiE != null && dialog.position == postion)
        {
            image.sprite = dialog.TachiE;
            image.preserveAspect = true;
        }

        if (dialog.b_together || dialog.position == postion)
            colorChange.Initialize(image.color, Color.white, 0.2f);
        else
            colorChange.Initialize(image.color, dullColor, 0.2f);

        if (image.sprite == null)
        {
            colorChange.Paused = true;
            image.color = Color.clear;
        }
    }

    private void OnGameStateChange(EGameState from, EGameState to)
    {
        switch (from)
        {
            case EGameState.Dialog:
            case EGameState.DialogInPerformance:
                Hide();
                break;
        }
    }

    public void Hide()
    {
        image.sprite = null;
        image.color = Color.clear;
    }

    private void OnShowSelection(List<string> list, DialogNode[] nodes)
    {
        if (image.sprite != null)
            colorChange.Initialize(image.color, dullColor, 0.2f);
    }

    private void SetColor(Color value)
    {
        image.color = value;
    }
}
